var jcrop_api;

function initUpload(){
	removeUnuseImage();
	closeModalEvent();	
}

function uploadImage(form, evtAfterDone){
	var percent = form.find('.percent');
	var percentVal = "0%";
	form.find("input[type=file]").change(function(){ form.submit();});
	form.ajaxForm({
		beforeSend: function() {
			var percentVal = '0%';
			percent.removeClass('hidden');
			percent.html(percentVal);
		},
		uploadProgress: function(event, position, total, percentComplete) {
			var percentVal = percentComplete + '%';
			percent.html(percentVal);
		},
		success: function() {
			var percentVal = '100%';
			percent.html(percentVal);
		},
		complete: function(xhr) {
			if(evtAfterDone!=undefined){
				evtAfterDone(xhr.responseText);
			} else {
				displayUploadImage(xhr.responseText);
			}
			percent.addClass('hidden');
			form.find('input[name=userfile]').val('');
		}
	});
}

function displayUploadImage(response){
	var data = $.parseJSON(response);
	if(data.code==1){
		var newImage = $('#temp-img-block').clone().removeAttr('id').removeClass('hidden');
		newImage.find('a.thumbnail').attr('data-name', data.file_name);
		newImage.find('img.media-object').attr('src', data.file_path);
		$('ul#image-temp').append(newImage);
		newImage.hide().fadeIn();
	} else {
		alert('Hình ảnh không hợp lệ');
	}
}

function showResizeImage(){
	if(typeof jcrop_api != typeof undefined){
		jcrop_api.destroy();
		$('.jcrop-holder').remove();
		$('#img-wrap img').removeAttr('style');
	}
	$('#crop-target').Jcrop({
		onChange:   showCoords,
		onSelect:   showCoords,
		onRelease:  clearCoords,
		setSelect:   [ 100, 100, 50, 50 ],
		aspectRatio: $('#crop-target').attr('data-ratio')
	},function(){
		jcrop_api = this;
	});
	$('#coords').on('change','input',function(e){
		var x1 = $('#x1').val(),
		x2 = $('#x2').val(),
		y1 = $('#y1').val(),
		y2 = $('#y2').val();
		jcrop_api.setSelect([x1,y1,x2,y2]);
	});
}

function showCoords(c){
	$('#x1').val(c.x);
	$('#y1').val(c.y);
	$('#x2').val(c.x2);
	$('#y2').val(c.y2);
	$('#w').val(c.w);
	$('#h').val(c.h);
}

function clearCoords(){
	$('#coords input').val('');
}

function getUploadedImage(response){
	var data = $.parseJSON(response);
	if(data.code==1){
		setCropImage(data.file_name, data.file_path);
	} else {
		alert(data.error.error);
	}
}

function setCropImage(file_name, file_path){
	$('#input-crop-path').val(file_name);
	$('.image-current').addClass('hidden');
	$('.image-resize').removeClass('hidden')
	.find('#crop-target')
	.attr({
		src: file_path,
		width: $('#img-wrap').width() +'px'
	});
	showResizeImage();
}

function doCropImage(callback){
	$('#btn-crop').click(function(){
		var form = $(this).closest('form');
		var fdata = form.serialize()
		+ '&crop[thumb_width]=' + $('#img-wrap').attr('data-thumb-width')
		+ '&crop[screen_width]=' + $('#img-wrap').attr('data-screen-width');
		$.ajax({
			url: form.attr('action'),
			type: 'POST',
			cache: false,
			data: fdata,
			success: function(data){
				callback(data);
			}
		});
	});
}

function removeUnuseImage(){
	$(document.body).on('mouseenter', '.img-block-edit', function(){
		var html = "<span class='img-remove' title='Xóa'><i class='glyphicon glyphicon-remove-sign'></i></span>";
		$(this).append(html);
		return;
	});
	$(document.body).on('mouseleave', '.img-block-edit', function(){
		$(this).find('span.img-remove').remove();
		return;
	});
	$(document.body).on('click', '.img-remove', function(e){
		e.preventDefault();
		var cur = $(this).parents('li');
		var pa  = $(this).parents('.img-block-edit');
		$.ajax({
			url: pa.attr('data-url-remove'),
			type: 'POST',
			data: {
				'name': pa.attr('data-name'),
				'folder': pa.attr('data-folder')
			},
			success: function(data){
				if(data.code==1){
					cur.fadeOut().remove();
				} else {
					alert(data.msg);
				}
			}
		});
		return false;
	});
}

function closeModalEvent(){
	$('#modal-change-image').on('hide.bs.modal', function () {
		$('#input-crop-path').val('');
		$('.image-current').removeClass('hidden');
		$('.image-resize').addClass('hidden');
	})
}